package yc.star.friend.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import yc.star.common.domain.TableDataInfo;
import yc.star.friend.domain.question.Question;
import yc.star.friend.domain.question.dto.QuestionQueryDTO;
import yc.star.friend.domain.question.es.QuestionES;
import yc.star.friend.domain.question.vo.QuestionDetailVO;
import yc.star.friend.domain.question.vo.QuestionVO;
import yc.star.friend.elasticsearch.QuestionRepository;
import yc.star.friend.manager.QuestionCacheManager;
import yc.star.friend.mapper.QuestionMapper;
import yc.star.friend.service.IQuestionService;

import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionCacheManager questionCacheManager;
    @Autowired
    private QuestionRepository questionRepository;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        // 将索引中的元素数量查出来
        long count = questionRepository.count();
        if (count <= 0) {
            // 代表ES中没有对应的数据,执行将数据库中的数据刷新到ES中
            refreshQuestion();
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum()-1,questionQueryDTO.getPageSize(),sort);
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty,pageable);
        } else if (difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(keyword,keyword,pageable);
        } else {
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword,keyword,difficulty,pageable);
        }
        long totalElements = questionESPage.getTotalElements();
        if (totalElements <= 0) {
            // 从ES中没有查出数据
            return TableDataInfo.empty();
        }
        List<QuestionES> questionESList = questionESPage.getContent();
        List<QuestionVO> questionVOS = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOS,totalElements);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        // 根据id将题目信息查出，如果没有，返回空
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null) {
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return questionDetailVO;
        }
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            return null;
        }
        refreshQuestion();
        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            // 代表题目缓存列表中没有数据
            // 将数据库中的数据同步
            questionCacheManager.refreshCache(); // 缓存刷新
        }
        // 查出该题目的上一题的题目id
        Long preQuestionId = questionCacheManager.preQuestion(questionId);
        return String.valueOf(preQuestionId);
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            // 代表题目缓存列表中没有数据
            // 将数据库中的数据同步
            questionCacheManager.refreshCache(); // 缓存刷新
        }
        // 查出该题目的下一题的题目id
        Long nextQuestionId = questionCacheManager.nextQuestion(questionId);
        return String.valueOf(nextQuestionId);
    }

    private void refreshQuestion() {
        // 在数据库中将所有题目数据都查出
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        // 将查出来的数据同步到ES中
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }

}